/*
 * buzzer.c
 *
 *  Created on: 2012-09-07
 *      Author: wojciech
 */

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

#include "buzzer.h"
#include "config.h"

static xQueueHandle xBUZZERQueue;

static void vBUZZERTask( void *pvParameters );

void vBUZZER_Init( void )
{
	BUZZER_DIR |= BIT(BUZZER);
	BUZZER_OFF;
	xBUZZERQueue = xQueueCreate(2, (unsigned portBASE_TYPE) sizeof (portBASE_TYPE));
	xTaskCreate( vBUZZERTask, ( signed char * ) "BUZ", BUZZER_TASK_STACKSIZE, ( void * ) NULL, 3, NULL );
}

void vBUZZER_Beep( uint32_t duration )
{
	xQueueSend(xBUZZERQueue, &duration, 0);
}

static void vBUZZERTask( void *pvParameters )
{
	(void)pvParameters;
	portBASE_TYPE i, beepDuration, beepCount;


	for(;;)
	{
		while(xQueueReceive(xBUZZERQueue, &beepDuration, 1000) != pdTRUE);
		beepCount = ((beepDuration & 0xC0000000) >> 30 )+ 1;
		beepDuration &= ~(0xC0000000);
		for(i = 0; i<beepCount; i++)
		{
			BUZZER_ON;
			vTaskDelay(beepDuration);
			BUZZER_OFF;
			vTaskDelay(20);
		}
	}
}
